package comm.serverhandle;

import comm.bean.GroupBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.Socket;

@Component
public class SocketClass {
    private static final Logger logger = LoggerFactory.getLogger(SocketClass.class);

    @Autowired
    GroupBean groupBean;

    Socket socket;

    public Socket getInstance()
    {
        if(this.socket != null && isServerClose(socket)){
            return this.socket;
        }else{
            try {
                this.socket = new Socket(groupBean.getTranspondHost(),groupBean.getTranspondPort());
            } catch (IOException e) {
//                e.printStackTrace();
                logger.error("请检查ip和端口是否正常！！！！！");
            }
            return this.socket;
        }
    }

    /**
     * 判断是否断开链接，断开返回false,没有返回true
     * @param socket
     * @return
     */
    public Boolean isServerClose(Socket socket){
        try {
            //发送1个字节的紧急数据，默认状况下，服务器端没有开启紧急数据处理，不影响正常通讯
            socket.sendUrgentData( 0xFF );
            return  true ;
        } catch (Exception se){
            return  false ;
        }
    }
}
